package leetcode;

/**
 * 19. 删除链表的倒数第N个节点
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/description/
 */
public class RemoveNthFormEnd {

    static class ListNode{
        int val;
        ListNode next;
        ListNode(int x){
            val = x;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n){
        ListNode root = head;
        ListNode curr = head;
        ListNode nth = null;
        int step = 0;
        while(curr != null){
            curr = curr.next;
            step++;
            if(step > n){
                if(nth == null){
                    nth = root;
                }else{
                    nth = nth.next;
                }
            }
        }
        if(nth == null){
            return root.next;
        }
        if(nth.next != null){
            nth.next = nth.next.next;
            return root;
        }else{
            return null;
        }
    }

    public static void main(String[] args) {
        int[] arr = {1,2};
        ListNode root = new ListNode(arr[0]);
        ListNode temp = root;
        for(int i = 1; i < arr.length; i++){
            ListNode node = new ListNode(arr[i]);
            temp.next = node;
            temp = node;
        }
        new RemoveNthFormEnd().removeNthFromEnd(root, 2);
    }

}
